﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mqtt.ClientAspCore.Options;
using Mqtt.ClientAspCore.Services;
using MQTTnet.Client.Options;
using System;

namespace Mqtt.ClientAspCore.Extensions
{
    public static class ServiceCollectionExtension
    {
        public static IServiceCollection AddMqttClientHostedService(this IServiceCollection services, IConfiguration configuration)
        {
            var host = configuration.GetSection("BrokerHostSettings:Host").Value;
            var port = Convert.ToInt32(configuration.GetSection("BrokerHostSettings:Port").Value);
            var clientId = configuration.GetSection("ClientSettings:Id").Value;
            var userName = configuration.GetSection("ClientSettings:UserName").Value;
            var password = configuration.GetSection("ClientSettings:Password").Value;
            services.AddMqttClientServiceWithConfig(aspOptionBuilder =>
            {
                aspOptionBuilder
                .WithCredentials(userName,password)
                .WithClientId(clientId)
                .WithTcpServer(host,port);
            });
            return services;
        }

        public static IServiceCollection AddMqttClientServiceWithConfig(this IServiceCollection services, Action<AspCoreMqttClientOptionBuilder> configure)
        {
            services.AddSingleton<IMqttClientOptions>(serviceProvider =>
            {
                var optionBuilder = new AspCoreMqttClientOptionBuilder(serviceProvider);
                configure(optionBuilder);
                return optionBuilder.Build();
            });
            services.AddSingleton<MqttClientService>();
            services.AddSingleton<IHostedService>(serviceProvider =>
            {
                return serviceProvider.GetService<MqttClientService>();
            });
            services.AddSingleton<MqttClientServiceProvider>(serviceProvider =>
            {
                var mqttClientService = serviceProvider.GetService<MqttClientService>();
                var mqttClientServiceProvider = new MqttClientServiceProvider(mqttClientService);
                return mqttClientServiceProvider;
            });
            return services;
        }
    }
}
